#include <stdio.h>
#include<math.h>
#include <stdlib.h>

int main()
{
	//打开文件，写入数据
	FILE* fin = fopen("data.txt", "w");
	if (fin == NULL)
	{
		perror("File: fin open fail");
		exit(-1);
	}

	printf("开始计算A类不确定度\n");
	//输入测量次数
	int num = -1;
	printf("请输入测量的次数:>");
	scanf("%d", &num);

	//开辟一个浮点型数组，存储测量值
	double* arr = (double*)malloc(sizeof(double) * num);

	double measure = 0;//测量值
	double sumplus = 0;//测量值总和
	int i = 1;
	while (num--)//计算测量之总和，之后求平均值
	{
		printf("请输入第一次%d测量值:>", i);
		scanf("%lf", &measure);

		arr[i - 1] = measure;//存储再数组中
		if (num > 0)
			i++;
		sumplus += measure;
	}
	double aver = sumplus / i;//平均值
	printf("平均值为:>%lf\n", aver);

	double subt = 0;//平均值和测量值的差值
	double sumMult = 0;//差值总乘积
	for (int j = 0; j < i; j++)
	{
		subt = (arr[j] - aver) * (arr[j] - aver);
		sumMult += subt;
	}

	double uA = sqrt(sumMult / (i * 1.0 * (i - 1)));
	printf("A类不确定度为:>%lf\n", uA);
	//写入文件
	fprintf(fin, "A类不确定度为:>%lf\n", uA);


	printf("开始计算B类不确定度\n");
	double range = 0;
	printf("请输入仪器的误差限:>");
	scanf("%lf", &range);
	double uB = range / sqrt(3.0);
	printf("B类不确定为:>%lf\n", uB);
	//写入文件
	fprintf(fin, "B类不确定度为:>%lf\n", uB);


	double Utotal = sqrt(uA * uA + uB * uB);
	printf("合成不确定度为%lf\n", Utotal);
	printf("合成不确定度的两倍为%lf\n", Utotal * 2);
	//写入文件
	fprintf(fin, "相对合成不确定度为:>%lf\n", (Utotal / aver) * 100 );
	fprintf(fin, "合成不确定度为:>%lf\n", Utotal);
	fprintf(fin, "合成不确定度的两倍为:>%lf\n", Utotal * 2);

	fclose(fin);

    free(arr);
	return 0;
}